import React, { useState } from 'react';
import { StyleSheet, ScrollView, View, TouchableOpacity } from 'react-native';
import { router } from 'expo-router';
import Toast from 'react-native-toast-message';
import * as ImagePicker from 'expo-image-picker';
import * as DocumentPicker from 'expo-document-picker';
import { MaterialIcons } from '@expo/vector-icons';
import {
  ThemedView,
  ThemedText,
  ThemedButton,
  ThemedInput,
  ThemedSelect,
  useTheme,
} from '../../components';
import { artworkService, fileService } from '../../utils/api/services';
import { ArtworkCreateRequest } from '../../utils/api/types';

const CATEGORIES = [
  { label: '图片作品', value: 'image' },
  { label: '视频作品', value: 'video' },
  { label: '音频作品', value: 'audio' },
  { label: '文本作品', value: 'text' },
  { label: '代码作品', value: 'code' },
];

// 添加文件选择结果类型
interface FileToUpload {
  uri: string;
  type: string;
  name: string;
}

export default function UploadScreen() {
  const { theme } = useTheme();
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [category, setCategory] = useState('');
  const [fileUrl, setFileUrl] = useState('');
  const [selectedFileName, setSelectedFileName] = useState('');
  const [tags, setTags] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [tagInput, setTagInput] = useState('');
  const [uploadMethod, setUploadMethod] = useState<'link' | 'file'>('link');

  // 处理文件选择
  const handleFilePick = async () => {
    try {
      let fileToUpload: FileToUpload;
      
      if (category === 'image') {
        // 请求相册权限
        const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
        if (status !== 'granted') {
          Toast.show({
            type: 'error',
            text1: '需要访问相册权限',
            text2: '请在设置中允许访问相册',
          });
          return;
        }

        const result = await ImagePicker.launchImageLibraryAsync({
          mediaTypes: ImagePicker.MediaTypeOptions.Images,
          allowsEditing: true,
          quality: 1,
        });

        if (!result.canceled && result.assets[0]) {
          fileToUpload = {
            uri: result.assets[0].uri,
            type: 'image/jpeg',
            name: 'image.jpg',
          };
          handleFileUpload(fileToUpload);
        }
      } else {
        // 使用文档选择器
        const result = await DocumentPicker.getDocumentAsync({
          type: '*/*',
          copyToCacheDirectory: true,
        });

        if (!result.canceled && result.assets?.[0]) {
          fileToUpload = {
            uri: result.assets[0].uri,
            type: result.assets[0].mimeType || 'application/octet-stream',
            name: result.assets[0].name,
          };
          handleFileUpload(fileToUpload);
        }
      }
    } catch (err) {
      console.error('File pick error:', err);
      Toast.show({
        type: 'error',
        text1: '选择文件失败',
        text2: '请重试',
      });
    }
  };

  // 处理文件上传
  const handleFileUpload = async (file: any) => {
    try {
      setLoading(true);
      const formData = new FormData();
      formData.append('file', file);

      const response = await fileService.uploadFile(formData);
      if (response?.data?.url) {
        setFileUrl(response.data.url);
        setSelectedFileName(file.name);
        Toast.show({
          type: 'success',
          text1: '文件上传成功',
        });
      }
    } catch (err) {
      console.error('File upload error:', err);
      Toast.show({
        type: 'error',
        text1: '文件上传失败',
        text2: '请重试',
      });
    } finally {
      setLoading(false);
    }
  };

  // 处理标签输入
  const handleTagInput = (text: string) => {
    setTagInput(text);
    if (text.endsWith(',') || text.endsWith(' ')) {
      const newTag = text.slice(0, -1).trim();
      if (newTag && !tags.includes(newTag)) {
        setTags([...tags, newTag]);
      }
      setTagInput('');
    }
  };

  const handleRemoveTag = (tagToRemove: string) => {
    setTags(tags.filter(tag => tag !== tagToRemove));
  };

  // 处理表单提交
  const handleSubmit = async () => {
    try {
      setLoading(true);
      setError('');

      if (!title || !category || !fileUrl) {
        setError('请填写必要信息和上传文件');
        return;
      }

      const artworkData: ArtworkCreateRequest = {
        title,
        description,
        file_url: fileUrl,
        file_type: category,
        category,
        tags,
      };

      await artworkService.createArtwork(artworkData);
      
      Toast.show({
        type: 'success',
        text1: '作品创建成功',
        text2: '即将返回首页',
        position: 'bottom',
        visibilityTime: 2000,
        autoHide: true,
        topOffset: 60,
        bottomOffset: 60,
        onShow: () => {
          setTitle('');
          setDescription('');
          setCategory('');
          setFileUrl('');
          setSelectedFileName('');
          setTags([]);
          setTagInput('');
        },
        onHide: () => {
          router.push('/');
        }
      });
    } catch (err) {
      console.error('Upload error:', err);
      Toast.show({
        type: 'error',
        text1: '创建失败',
        text2: '请检查输入并重试',
      });
      setError('创建失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <ScrollView 
      style={[styles.container, { backgroundColor: theme.colors.background }]}
      contentContainerStyle={styles.scrollContent}
      showsVerticalScrollIndicator={false}
      bounces={false}
    >
      <ThemedView variant="card" style={styles.content}>
        <ThemedText variant="h1" style={styles.title}>
          上传作品
        </ThemedText>

        <ThemedInput
          value={title}
          onChangeText={setTitle}
          placeholder="请输入作品标题"
          style={styles.input}
        />

        <ThemedInput
          value={description}
          onChangeText={setDescription}
          placeholder="请输入作品描述"
          multiline
          numberOfLines={4}
          style={[styles.input, styles.multilineInput]}
        />

        <ThemedSelect
          value={category}
          onValueChange={(value) => {
            setCategory(value);
            setFileUrl('');
            setSelectedFileName('');
          }}
          items={CATEGORIES}
          placeholder="请选择作品类别"
          style={styles.input}
        />

        <View style={styles.uploadMethodContainer}>
          <TouchableOpacity
            style={[
              styles.methodButton,
              uploadMethod === 'link' && { backgroundColor: theme.colors.primary },
            ]}
            onPress={() => setUploadMethod('link')}
          >
            <ThemedText style={{ 
              fontSize: 16, 
              fontWeight: '500',
              color: uploadMethod === 'link' ? '#FFFFFF' : theme.colors.text,
            }}>
              链接上传
            </ThemedText>
          </TouchableOpacity>
          <TouchableOpacity
            style={[
              styles.methodButton,
              uploadMethod === 'file' && { backgroundColor: theme.colors.primary },
            ]}
            onPress={() => setUploadMethod('file')}
          >
            <ThemedText
              style={{
                fontSize: 16,
                fontWeight: '500',
                color: uploadMethod === 'file' ? '#FFFFFF' : theme.colors.text,
              }}
            >
              文件上传
            </ThemedText>
          </TouchableOpacity>
        </View>

        {uploadMethod === 'link' ? (
          <ThemedInput
            value={fileUrl}
            onChangeText={setFileUrl}
            placeholder="请输入文件链接"
            style={styles.input}
          />
        ) : (
          <View style={styles.fileUploadContainer}>
            <ThemedButton
              title={selectedFileName || "选择文件"}
              onPress={handleFilePick}
              loading={loading}
              style={styles.filePickButton}
              leftIcon={
                <MaterialIcons
                  name="file-upload"
                  size={24}
                  color={theme.colors.primary}
                />
              }
            />
            {selectedFileName && (
              <ThemedText style={styles.fileName}>
                已选择: {selectedFileName}
              </ThemedText>
            )}
          </View>
        )}

        <ThemedInput
          value={tagInput}
          onChangeText={handleTagInput}
          placeholder="输入标签，用逗号或空格分隔"
          style={styles.input}
        />

        {tags.length > 0 && (
          <ThemedView style={styles.tagsContainer}>
            {tags.map((tag) => (
              <ThemedView
                key={tag}
                variant="card"
                style={styles.tagItem}
              >
                <ThemedText variant="caption">
                  {tag}
                </ThemedText>
                <ThemedButton
                  title="×"
                  onPress={() => handleRemoveTag(tag)}
                  style={styles.removeTagButton}
                  textStyle={styles.removeTagButtonText}
                  variant="outline"
                />
              </ThemedView>
            ))}
          </ThemedView>
        )}

        {error ? (
          <ThemedText 
            variant="body" 
            style={{ 
              ...styles.error, 
              color: theme.colors.error 
            }}
          >
            {error}
          </ThemedText>
        ) : null}

        <ThemedButton
          title="提交作品"
          onPress={handleSubmit}
          loading={loading}
          disabled={loading || !title || !category || !fileUrl}
          style={styles.submitButton}
        />
      </ThemedView>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  scrollContent: {
    minHeight: '100%',
  },
  content: {
    minHeight: '100%',
    padding: 16,
  },
  title: {
    marginBottom: 24,
    textAlign: 'center',
  },
  input: {
    marginBottom: 16,
  },
  multilineInput: {
    height: 120,
    textAlignVertical: 'top',
    paddingTop: 12,
  },
  uploadMethodContainer: {
    flexDirection: 'row',
    marginBottom: 16,
    borderRadius: 8,
    overflow: 'hidden',
  },
  methodButton: {
    flex: 1,
    paddingVertical: 12,
    alignItems: 'center',
    justifyContent: 'center',
  },
  methodButtonText: {
    fontSize: 16,
    fontWeight: '500',
  },
  fileUploadContainer: {
    marginBottom: 16,
  },
  filePickButton: {
    width: '100%',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
  },
  fileName: {
    marginTop: 8,
    textAlign: 'center',
    fontSize: 14,
  },
  submitButton: {
    marginTop: 24,
  },
  error: {
    marginTop: 16,
    textAlign: 'center',
  },
  tagsContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    marginBottom: 16,
    marginTop: -8,
  },
  tagItem: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 8,
    paddingVertical: 4,
    marginRight: 8,
    marginTop: 8,
  },
  removeTagButton: {
    height: 20,
    width: 20,
    padding: 0,
    marginLeft: 4,
  },
  removeTagButtonText: {
    fontSize: 14,
    marginTop: -2,
  },
}); 